///
///   针对element-ui表单，前后台模型对应
///

const array_value_type = ['CHECKBOX', 'FILE']

/**
 * 初始化表单模型
 * @param {Object} formInfo 
 */
export function initForm(formInfo) {
  const form = formInfo
  for (var i in form.fields) {
    form.fields[i].value = array_value_type.indexOf(form.fields[i].type) >= 0 ? [] : ''
  }
  return form
}
/**
 * 初始化数据模型
 * @param {Object} formInfo 
 */
export function initData(data) {
  for (var i in data.items) {
    const item = data.items[i]
    data.items[i].value = array_value_type.indexOf(item.fieldInfo.type) >= 0 ? JSON.parse(item.value) : item.value
  }
  return data
}

/**
 * 将前台表单模型转换成后台数据模型
 * @param {Object} formData 
 */
export function convertToData(formData) {
  const data = {id: formData.id, name: formData.name, items: []}
  for (var i in formData.fields) {
    const field = formData.fields[i]
    // 精简file类型数据模型
    if (field.type === 'FILE' && field.value.length > 0) {
      const files = []
      for (var j in field.value) {
        const tmp = field.value[j]
        if (tmp.response) {
          files.push({name: tmp.response.name, url: tmp.response.url, size: tmp.response.size})
        } else {
          files.push(tmp)
        }
      }
      field.value = files
    }
    data.items.push({ fieldInfo: {id:field.id}, value: field.value })
  }
  return data
}

/**
 * 将后台数据模型转换成前台表单模型
 * @param {Object} data 
 */
export function convertToForm(data) {
  const form = data
  form.fields = []
  for (var i in form.items) {
    const item = form.items[i]
    form.fields[i] = item.fieldInfo
    form.fields[i].value = item.value
    if (array_value_type.indexOf(item.fieldInfo.type) >= 0) {
      form.fields[i].value = item.value ? JSON.parse(item.value) : []
    }
  }
  delete form.items
  return form
}
